<?php
/**
 * Created by PhpStorm.
 * User: hebidu
 * Date: 15/7/3
 * Time: 20:22
 */

namespace app\index\controller;

use app\extend\crypt\DesCrypt;
use app\index\exception\ApiException;
use app\oauth2\api\ClientsApi;
use think\controller\Rest;
use app\utils\CryptUtils;
use app\index\model\ErrorCode;
use think\Exception;
use think\Input;
use think\Log;
use think\Response;


/**
 * 接口基类
 * Class Base
 *
 * @author 老胖子-何必都 <hebiduhebi@126.com>
 * @package app\index\Controller
 */
abstract class Base extends Rest{

    protected $encrypt_key = "";
    protected $client_id = "";
    protected $client_secret = "";
    protected $notify_id = "";

    protected $allow_controller = array('token','file','alipay_app','alipay_refund','wxpay_app','alipay_direct');

    /**
     * 构造函数
     */
    public function __construct(){
        parent::__construct();
        header("X-Copyright:http://www.itboye.com");

        if(!defined("CONTROLLER_NAME") || ( !in_array(strtolower(CONTROLLER_NAME),$this->allow_controller) &&  strtolower(CONTROLLER_NAME) != "index" )){
            $this->apiReturnErr(ErrorCode::Not_Found_Resource,"请求资源不存在!");
        }

        if(method_exists($this,"_initialize")){
            $this->getClientID();
            $this->decodePost();
            $this->_initialize();
        }

        // fix ：周舟 ：2016/6/29
        // 支付回掉 bug
        // else{
        //     throw new ApiException("未实现_initialize");
        // }
    }

    protected function getClientID(){
        $client_id = $this->_get("client_id","");
        if(empty($client_id)){
            $client_id = $this->_post("client_id","");
            unset($_POST['client_id']);
        }

        if(empty($client_id)){
            $this->apiReturnErr("缺失client_id!",ErrorCode::Lack_Parameter);
        }

        $_GET['client_id'] = $client_id;

        $this->client_id = $client_id;
        unset($_POST['client_id']);
    }

    protected function decodePost(){

        $api = new ClientsApi();

        $result = $api->getInfo(array('client_id'=>$this->client_id));

        if($result['status'] && is_array($result['info'])){
            $this->client_secret = $result['info']['client_secret'];
        }else{
            $this->apiReturnErr('无效的Client_ID',ErrorCode::Invalid_Parameter);
        }
// addLog($this->client_secret,$_GET,$_POST,"获取到参数");
        $post = $this->_post('itboye','');
        $search = array(" ","　","\n","\r","\t");
        $replace = array("","","","","");
        $post = str_replace($search, $replace, $post);
        // $post = preg_replace('/\\\\n/', '', $post);
        $from = $this->_get('from','');
        // if($from == 'android'){
// addLog($this->client_secret,"decodePost",$post,"pre [itboye解密]");
        // }
        $data = DesCrypt::decode(base64_decode($post),$this->client_secret);
// addLog($this->client_secret,$data, $post, "decodePost [itboye解密]");
        $data = $this->filter_post($data);
// addLog($this->client_secret,$data, $post, "filterPost [itboye解密]");
        // if($from == 'android') {
        // }
        $obj = json_decode($data,JSON_OBJECT_AS_ARRAY);
        $_POST = $obj;
// addLog("decodePost",trim($data),$obj,"decodePost [itboye解密完毕]");

    }

    /**
     * 过滤末尾多余空白符 ASCII码等于7的奇怪符号
     * @param $post
     * @return string
     */
    protected function filter_post($post){
        $post = trim($post);
        for ($i=strlen($post)-1;$i>=0;$i--) {
            $ord = ord($post[$i]);
            if($ord > 31 && $ord != 127){
                $post = substr($post,0,$i+1);
                return $post;
            }
        }
        return $post;
    }

    /**
     * 返回加密后的数据
     * @access protected
     * @param mixed $data 要返回的数据，未加密
     * @return array
     */
     protected function ajaxReturn($data) {

        $code = $data['code'];
        if($code == 0){
            $type = "T";
        }else{
            $type = "F";
        }

        $data = CryptUtils::encrypt($data);
        $now = time();
        if(empty($this->notify_id)){
            $this->notify_id = $now;
        }
        $param = array(
            'client_secret' =>$this->client_secret,
            'client_id'     =>$this->client_id,
            'data'          =>$data,
            'notify_id'     =>$this->notify_id,
            'time'          =>strval($now),
            'type'          =>$type,
            'alg'           =>'md5',
        );

        $param['sign'] = CryptUtils::sign($param);
        unset($param['client_secret']);
        Response::isExit(true);
        Response::send($param,"json",false);

    }

    /**
     * ajax返回
     * @param $data
     * @internal param $i
     * @return array
     */
    protected function apiReturnSuc($data){
        $this->ajaxReturn(array('code'=>0,'data'=>$data,'notify_id'=>$this->notify_id));
    }

    /**
     * ajax返回，并自动写入token返回
     * @param $data
     * @param int $code
     * @internal param $i
     * @return array
     */
    protected function apiReturnErr($data,$code=-1){
        $this->ajaxReturn(array('code'=>$code,'data'=>$data,'notify_id'=>$this->notify_id));
    }

    public function _param($key,$default='',$emptyErrMsg=''){
        $value = Input::post($key,$default);
        addLog("File/upload","UID=".$value,$_POST,$this->client_id."调用文件上传接口!");

        if($value == $default){
            $value =  Input::get($key,$default);
        }
        addLog("File/upload","UID=".$value,$_POST,$this->client_id."调用文件上传接口!");

        if($default == $value && !empty($emptyErrMsg)){
            $this->apiReturnErr($emptyErrMsg);
        }
        return $value;
    }

    /**
     * @param $key
     * @param string $default
     * @param string $emptyErrMsg  为空时的报错
     * @return mixed
     */
    public function _post($key,$default='',$emptyErrMsg=''){
        $value = I("post.".$key,$default);

        if($default == $value && !empty($emptyErrMsg)){
            $this->apiReturnErr($emptyErrMsg);
        }
        return $value;
    }

    /**
     * @param $key
     * @param string $default
     * @param string $emptyErrMsg  为空时的报错
     * @return mixed
     */
    public function _get($key,$default='',$emptyErrMsg=''){
        $value = I("get.".$key,$default);

        if($default == $value && !empty($emptyErrMsg)){
            $this->apiReturnErr($emptyErrMsg);
        }
        return $value;
    }




}